package com.cdream.basic.java8;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.cdream.basic.java8.model.OrderDO;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

import static com.cdream.basic.java8.StreamExample.COMPLETE;
import static java.math.BigDecimal.ONE;

/**
 * @author cdream
 * @date 2020-06-14
 */
public class OptionalExample {
    public static void main(String[] args) {
        List<BigDecimal> resultList = CollUtil.newArrayList();
        OrderDO orderDO = OrderDO.builder().id(1).state(COMPLETE).createTime(DateUtil.parse("20200101")).totalAccount(ONE).build();
        // 1. 存在在开干
        Optional<OrderDO> orderDOOptional = Optional.ofNullable(orderDO);
        orderDOOptional.ifPresent(a-> System.out.println(a));
        // 2. 存在返回，不存在返回默认
        BigDecimal totalAccount = orderDOOptional.map(a -> a.getTotalAccount()).orElse(BigDecimal.ZERO);
        // 3. 存在在返回，不存在则由函数生成
        BigDecimal bigDecimal = orderDOOptional.map(a -> a.getTotalAccount()).orElseGet(() -> BigDecimal.ZERO);
        // 4. 俄罗斯套娃
        orderDOOptional.map(a->a.getTotalAccount()).ifPresent(a->resultList.add(a));
        // 5. 无可奈何
        if (orderDOOptional.isPresent()){
            // 业务逻辑
        }
    }
}
